<script>
	import Crypto from '@/common/upload/crypto.js';
	import '@/common/upload/hmac.js';
	import '@/common/upload/sha1.js';
	var socketTimer = null;
	let timers = null;
	import {
		Base64
	} from '@/common/upload/base64.js';
	var uploadFileSize = 1024 * 1024 * 100; // 上传文件的大小限制100m
	var policyText = {
		"expiration": "2099-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
		"conditions": [
			["content-length-range", 0, uploadFileSize] // 设置上传文件的大小限制 
		]
	};
	var accessid = "LTAI5tPpTW26Ug49nBPaPM3Z";
	//自己去申请
	var accesskey = "OdnQOjtE27vFtDlLYXqhLPzMIydDLo"
	//自己去申请
	var osshost = 'https://ruomian.oss-cn-chengdu.aliyuncs.com';
	var policyBase64 = Base64.encode(JSON.stringify(policyText));
	var message = policyBase64;
	var bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, {
		asBytes: true
	});
	var signature = Crypto.util.bytesToBase64(bytes);
	var timetamp = new Date().getTime();

	function random_string(len) {
		len = len || 32;
		var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
		var maxPos = chars.length;
		var pwd = '';
		for (let i = 0; i < len; i++) {
			pwd += chars.charAt(Math.floor(Math.random() * maxPos));
		}
		return pwd;
	}
	import checkappupdate from 'common/checkappupdate.js';
	export default {
		globalData: {
			imgBaseUrl: "https://ruomian.oss-cn-chengdu.aliyuncs.com/",
			phoneReg: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
			videoThumb: "?x-oss-process=video/snapshot,t_0,f_jpg",
			latitude: "",
			// connectUrl: "wss://3020.zhouyangjun.com:8282",
			connectUrl: "wss://www.ruomiankj.com:8282",
			longitude: "",
			shareType: "",
			shareProId: "",
			cpid: "", //测评id
			shareid: "", //分享人id
			tgid: "", //团购id
			mdid: "", //门店id
			appSync: {},
			hideFlag: false,
			dxFlag: false,
			pushObj: {},
			updateFlag:false,
			type:"",
			nrid:""
		},
		onLaunch: function(options) {
			console.log(options, "`````````````````````````")
			uni.removeStorageSync("cityData");
			// #ifdef MP-WEIXIN
			if (options.query.shareid) {
				this.globalData.shareid = options.query.shareid;
			}
			if (options.query.cpid) {
				this.globalData.cpid = options.query.cpid;
			}
			if (options.query.tgid) {
				this.globalData.tgid = options.query.tgid;
			}
			if (options.query.mdid) {
				this.globalData.mdid = options.query.mdid;
			}
			// if (options.query.q) {
			// 	let q = decodeURIComponent(options.query.q);
			// 	if (q.indexOf("?") != -1) {
			// 		if (this.getArgs(q, "shareid")) {
			// 			this.globalData.shareid = this.getArgs(q, "shareid");
			// 		}
			// 		if (this.getArgs(q, "cpid")) {
			// 			this.globalData.cpid = this.getArgs(q, "cpid");
			// 		}
			// 		if (this.getArgs(q, "tgid")) {
			// 			this.globalData.tgid = this.getArgs(q, "tgid");
			// 		}
			// 		if (this.getArgs(q, "mdid")) {
			// 			this.globalData.mdid = this.getArgs(q, "mdid");
			// 		}
			// 		let type = this.getArgs(q, "type");
			// 		if(type=='cp'){
			// 			uni.navigateTo({
			// 				url:"/pages/pageone/pages/ActivityDetails/ActivityDetails?id="+this.globalData.cpid
			// 			})
			// 		}
			// 		if(type=='tg'){
			// 			uni.navigateTo({
			// 				url:"/pages/pagethree/pages/OfferDetails/OfferDetails?id="+this.globalData.tgid
			// 			})
			// 		}
			// 		if(type=='tpnr'){
			// 			uni.navigateTo({
			// 				url:"/pages/pagetwo/pages/FindDetail/FindDetail?id="+this.getArgs(q, "nrid")
			// 			})
			// 		}
			// 		if(type=='spnr'){
			// 			uni.navigateTo({
			// 				url:"/pages/pagefive/pages/VideoDetail/VideoDetail?id="+this.getArgs(q, "nrid")
			// 			})
			// 		}
			// 		if(type=='gr'){
			// 			uni.navigateTo({
			// 				url:"/pages/pageone/pages/Business-card/Business-card?id="+this.getArgs(q, "usid")
			// 			})
			// 		}
			// 	}
			// }
			// #endif
      var platform = uni.getSystemInfoSync().platform;
      //#ifdef APP-PLUS

      // const _handlePushReceive = function(message) {
      //   console.log(message)
      //   console.log("222222222222222222222222222222")
      //   // 消息接收事件，手动创造本地通知信息
      //   plus.push.createMessage(JSON.parse(message.content).msg,JSON.stringify(message.payload) , {
      //     title: message.title,
      //     content: message.content,
      //   })
      // };
      // plus.push.addEventListener('receive', _handlePushReceive);


      /* 5+  push 消息推送 ps:使用:H5+的方式监听，实现推送*/
      plus.push.addEventListener("click", function(msgc) {
        console.log(msgc);
        console.log("++++++++++++++++++++++++++++++++++++++");
        if (platform == 'ios') {
          //离线是payload为object , 在线时本地创建的为string(本地创建通知只能传string，否则无法传递payload)
          if (typeof msgc.payload == 'string') {
            console.log('string')
            var paymsg = JSON.parse(msgc.payload);
          } else {
            console.log('obj')
            var paymsg = msgc.payload;
          }
          console.log(paymsg)
          //执行跳转判断
        }
        //这里可以写跳转业务代码
      }, false);
      // 监听在线消息事件
      plus.push.addEventListener("receive", function(msg) {
        //这里可以写跳转业务代码
        console.log(msg)
        console.log("-----------------------------------============================")

        console.log(platform)
        // if (msg.type == "receive") {
          if (platform == 'ios') {
            // console.log(msg.payload)
            plus.push.createMessage(
                msg.payload.content,
                //本地创建通知payload只能传string，否则无法成功传递（为null）
                JSON.stringify(msg.payload), {
                  cover: false,
                  title: msg.title,
                });
          }
        // }
        if (platform == 'android') {
          //执行跳转判断
        }
      }, false);
      //#endif

      // #ifdef APP
			checkappupdate.check({
				title: '检测到有新版本！',
				content: '请升级app到最新版本！',
				canceltext: '暂不升级',
				oktext: '立即升级'
			});
			var args = plus.runtime.arguments;
			if (args) {
				console.log(args)
				// 处理args参数，如直达到某新页面等  
				let q = args;
				if (q.indexOf("?") != -1) {
					if (this.getArgs(q, "shareid")) {
						this.globalData.shareid = this.getArgs(q, "shareid");
					}
					if (this.getArgs(q, "cpid")) {
						this.globalData.cpid = this.getArgs(q, "cpid");
					}
					if (this.getArgs(q, "tgid")) {
						this.globalData.tgid = this.getArgs(q, "tgid");
					}
					if (this.getArgs(q, "mdid")) {
						this.globalData.mdid = this.getArgs(q, "mdid");
					}
					let type = this.getArgs(q, "type");
					this.globalData.type = this.getArgs(q, "mdid");
					if (type == 'cp') {
						uni.navigateTo({
							url: "/pages/pageone/pages/ActivityDetails/ActivityDetails?id=" + this.globalData
								.cpid
						})
					}
					if (type == 'tg') {
						uni.navigateTo({
							url: "/pages/pagethree/pages/OfferDetails/OfferDetails?id=" + this.globalData.tgid
						})
					}
					if (type == 'tpnr') {
						this.globalData.nrid = this.getArgs(q, "nrid");
						uni.navigateTo({
							url: "/pages/pagetwo/pages/FindDetail/FindDetail?id=" + this.getArgs(q, "nrid")
						})
					}
					if (type == 'spnr') {
						this.globalData.nrid = this.getArgs(q, "nrid");
						uni.navigateTo({
							url: "/pages/pagefive/pages/VideoDetail/VideoDetail?id=" + this.getArgs(q, "nrid")
						})
					}
					if (type == 'gr') {
						uni.navigateTo({
							url: "/pages/pageone/pages/Business-card/Business-card?id=" + this.getArgs(q,
								"usid")
						})
					}
				}
			}
			// #endif
			if (uni.getStorageSync("rmToken")) {
				this.createConnect();
				this.sendMessage({
					"contacts": 2
				});
				if (this.globalData.latitude) {
					let posObj = {};
					posObj.dimension = this.globalData.latitude;
					posObj.longitude = this.globalData.longitude;
					this.sendMessage(posObj)
				} else {
					this.indexInitFun().then(res => {
						let posObj = {};
						posObj.dimension = this.globalData.latitude;
						posObj.longitude = this.globalData.longitude;
						this.sendMessage(posObj)
					})
				}
			}
			this.getLocation();
			if (uni.getStorageSync("rmToken") && this.globalData.dxFlag) {
				this.createConnect();
				this.sendMessage({
					"contacts": 2
				});
				if (this.globalData.latitude) {
					let posObj = {};
					posObj.dimension = this.globalData.latitude;
					posObj.longitude = this.globalData.longitude;
					this.sendMessage(posObj)
				} else {
					this.indexInitFun().then(res => {
						let posObj = {};
						posObj.dimension = this.globalData.latitude;
						posObj.longitude = this.globalData.longitude;
						this.sendMessage(posObj)
					})
				}
			}
			// let that = this;
			// uni.getLocation({
			//     type: 'wgs84',
			//     success: function (res) {
			//         console.log('当前位置的经度：' + res.longitude);
			//         console.log('当前位置的纬度：' + res.latitude);
			// 				that.longitude = res.longitude
			// 				that.latitude = res.latitude
			// 				alert(res.longitude,res.latitude)
			//     }
			// })
		},
		onShow: function() {
			console.log('App Show')
			// this.globalData.hideFlag = false;
			clearTimeout(timers)
			// #ifdef APP
			// 推送信息
			plus.push.getClientInfoAsync(res => {
				this.globalData.pushObj = res;
			}, err => {
			});
			var args = plus.runtime.arguments;
      console.log("参数参数参数参数参数参数参数")
      console.log(args)
			if (args) {
				// 处理args参数，如直达到某新页面等  
				let q = args;
				if (q.indexOf("?") != -1) {
					if (this.getArgs(q, "shareid")) {
						this.globalData.shareid = this.getArgs(q, "shareid");
					}
					if (this.getArgs(q, "cpid")) {
						this.globalData.cpid = this.getArgs(q, "cpid");
					}
					if (this.getArgs(q, "tgid")) {
						this.globalData.tgid = this.getArgs(q, "tgid");
					}
					if (this.getArgs(q, "mdid")) {
						this.globalData.mdid = this.getArgs(q, "mdid");
					}
					let type = this.getArgs(q, "type");
					if (type == 'cp') {
						uni.navigateTo({
							url: "/pages/pageone/pages/ActivityDetails/ActivityDetails?id=" + this.globalData
								.cpid
						})
					}
					if (type == 'tg') {
						uni.navigateTo({
							url: "/pages/pagethree/pages/OfferDetails/OfferDetails?id=" + this.globalData.tgid
						})
					}
					if (type == 'tpnr') {
						uni.navigateTo({
							url: "/pages/pagetwo/pages/FindDetail/FindDetail?id=" + this.getArgs(q, "nrid")
						})
					}
					if (type == 'spnr') {
						uni.navigateTo({
							url: "/pages/pagefive/pages/VideoDetail/VideoDetail?id=" + this.getArgs(q, "nrid")
						})
					}
					if (type == 'gr') {
						uni.navigateTo({
							url: "/pages/pageone/pages/Business-card/Business-card?id=" + this.getArgs(q,
								"usid")
						})
					}
				}
			}
			// #endif
			
			this.$u.api.commonDetails({
				name: "service_charge_percentage"
			}).then(res => {
				this.globalData.appSync = res.data.details;
			})
		},
		onHide: function() {
			console.log('App Hide')
			this.globalData.hideFlag = true;
			timers = setTimeout(() => {
				uni.closeSocket({
					reason: "khdClose"
				})
			}, 60000)
		},
		methods: {
			setBadge(num){
				// #ifdef APP
				plus.runtime.setBadgeNumber(num);
				// #endif
			},
			clearBadge(){
				// #ifdef APP
				plus.runtime.setBadgeNumber(0);
				// #endif
			},
			loadMsg() {
				return new Promise((resolve, reject) => {
					let _this = this;
					uni.connectSocket({
						url: _this.globalData.connectUrl,
						success: res => {
							console.log(res)
							
						}
					});
					uni.onSocketOpen(function(res) {
						_this.globalData.hideFlag = false;
						_this.globalData.dxFlag = false;
						resolve();
						_this.sendMessage({
							connect: "keep connected"
						});
						if (uni.getStorageSync("rmToken")) {
							_this.sendMessage({
								"contacts": 2
							});
						}
						if (_this.globalData.latitude) {
							let posObj = {};
							posObj.dimension = _this.globalData.latitude;
							posObj.longitude = _this.globalData.longitude;
							_this.sendMessage(posObj)
						} else {
							_this.indexInitFun().then(res => {
								let posObj = {};
								posObj.dimension = _this.globalData.latitude;
								posObj.longitude = _this.globalData.longitude;
								_this.sendMessage(posObj)
							})
						}
						socketTimer = setInterval(() => {
							_this.sendMessage({
								connect: "keep connected"
							});
						}, 30000)
					});
					uni.onSocketMessage(function(res) {
						console.log(res)
						if (res.data == 'khdClose') {
							_this.globalData.dxFlag = true;
						} else {
							let data = JSON.parse(res.data);
							if (data.state == 2 && data.num > 0) {
								_this.globalData.msgNum = data.num;
								uni.setTabBarBadge({
									index: 2,
									text: _this.globalData.msgNum.toString()
								});
								_this.setBadge(Number(_this.globalData.msgNum));
							} else if (data.state == 2 && data.num == 0) {
								_this.globalData.msgNum = data.num;
								uni.hideTabBarRedDot({
									index: 2
								})
								_this.clearBadge();
							}
							if (data.vice_user_id == uni.getStorageSync("userId")) {
								_this.globalData.msgNum = Number(_this.globalData.msgNum) + 1;
								uni.setTabBarBadge({
									index: 2,
									text: _this.globalData.msgNum.toString()
								});
								_this.setBadge(Number(_this.globalData.msgNum));
							}
						}
					
					});
					uni.onSocketError(function(res) {
						console.log('WebSocket连接打开失败，请检查！');
					});
					uni.onSocketClose(function(res) {
						console.log(res)
						_this.globalData.dxFlag = true;
						if (res.reason == 'khdClose') {
							
						} else {
							uni.connectSocket({
								url: _this.globalData.connectUrl,
								success: res => {
									console.log(res)
									_this.globalData.dxFlag = false;
								}
							});
						}
					})
				})
			},
			getArgs(url, name) {
				let str = url.split("?")[1];
				let arr = str.split("&");
				let obj = {};
				for (let i = 0; i < arr.length; i++) {
					obj[arr[i].split("=")[0]] = arr[i].split("=")[1];
				}
				return obj[name];
			},
			sendMessage(data) {
				data.token = uni.getStorageSync("rmToken");
				data = JSON.stringify(data);
				console.log(data)
				uni.sendSocketMessage({
					data
				})
			},
			createConnect() {
				this.$u.api.labelList({
					type: 5,
					page: 1,
					limit: 1
				}).then(res => {
					let _this = this;
					uni.connectSocket({
						url: _this.globalData.connectUrl,
						success: res => {
							console.log(res)
							_this.globalData.dxFlag = false;
						}
					});
					uni.onSocketOpen(function(res) {
						_this.globalData.hideFlag = false;
						_this.sendMessage({
							connect: "keep connected"
						});
						if (uni.getStorageSync("rmToken")) {
							_this.sendMessage({
								"contacts": 2
							});
						}
						if (_this.globalData.latitude) {
							let posObj = {};
							posObj.dimension = _this.globalData.latitude;
							posObj.longitude = _this.globalData.longitude;
							_this.sendMessage(posObj)
						} else {
							_this.indexInitFun().then(res => {
								let posObj = {};
								posObj.dimension = _this.globalData.latitude;
								posObj.longitude = _this.globalData.longitude;
								_this.sendMessage(posObj)
							})
						}
						socketTimer = setInterval(() => {
							_this.sendMessage({
								connect: "keep connected"
							});
						}, 30000)
					});
					uni.onSocketMessage(function(res) {
						console.log(res)
						if (res.data == 'khdClose') {
							_this.globalData.dxFlag = true;
						} else {
							let data = JSON.parse(res.data);
							if (data.state == 2 && data.num > 0) {
								_this.globalData.msgNum = data.num;
								uni.setTabBarBadge({
									index: 2,
									text: _this.globalData.msgNum.toString()
								});
								_this.setBadge(Number(_this.globalData.msgNum));
							} else if (data.state == 2 && data.num == 0) {
								_this.globalData.msgNum = data.num;
								uni.hideTabBarRedDot({
									index: 2
								})
								_this.clearBadge();
							}
							if (data.vice_user_id == uni.getStorageSync("userId")) {
								_this.globalData.msgNum = Number(_this.globalData.msgNum) + 1;
								uni.setTabBarBadge({
									index: 2,
									text: _this.globalData.msgNum.toString()
								});
								_this.setBadge(Number(_this.globalData.msgNum));
							}
						}

					});
					uni.onSocketError(function(res) {
						console.log('WebSocket连接打开失败，请检查！');
					});
					uni.onSocketClose(function(res) {
						console.log(res)
						_this.globalData.dxFlag = true;
						if (_this.globalData.hideFlag) {
							
						} else {
							uni.connectSocket({
								url: _this.globalData.connectUrl,
								success: res => {
									console.log(res)
									_this.globalData.dxFlag = false;
								}
							});
						}
					})
				})
			},
			checkAuth(type) {
				return new Promise((resolve, reject) => {
					uni.getSetting({
						success: res => {
							if (res.authSetting[type] != undefined && res.authSetting[type] != true) {
								resolve(false)
							} else {
								resolve(true)
							}
						}
					})
				})
			},
			//检查是否授权
			checkGetLaction() {
				var that = this;
				uni.getSetting({
					success(res) {
						if (res.authSetting['scope.userLocation'] != undefined && res.authSetting[
								'scope.userLocation'] != true) {
							uni.showModal({
								title: '是否授权当前位置',
								content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
								success: function(res) {
									if (res.cancel) {
										console.log('取消授权')
										that.globalData.latitude = -48.526;
										that.globalData.longitude = -123.236;
									} else if (res.confirm) {
										console.log('授权成功')
										uni.openSetting({
											success: function(data) {
												console.log(data)
												if (data.authSetting[
														"scope.userLocation"] == true) {
													uni.showToast({
														title: '授权成功',
														icon: 'success',
														duration: 2000
													})
													that.getLocation()

												} else {
													uni.showToast({
														title: '授权失败',
														icon: 'success',
														duration: 5000
													})
												}
											}
										})
									}
								},
								fail: err => {
									console.log(err, 99999999)
								}
							})
						}
					}
				})
			},
			isImage(ext) {
				var index = ext.lastIndexOf(".");
				//获取后缀
				var urls = ext.substr(index + 1);
				return ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'].indexOf(urls.toLowerCase()) !== -
					1;
			},
			getImgBase(url) {
				// #ifdef APP
				return new Promise((resolve, reject) => {
					let toBase64Url;
					uni.request({
						url: url,
						method: 'GET',
						responseType: "arraybuffer",
						success: res => {
							// console.log(res)
							let base64 = uni.arrayBufferToBase64(res.data); //把arraybuffer转成base64
							toBase64Url = 'data:image/jpeg;base64,' + base64; //不加上这串字符，在页面无法显示
							resolve(toBase64Url);
						}
					});
				})
				// #endif
				// #ifdef MP-WEIXIN
				console.log(url)
				return new Promise((resolve, reject) => {
					uni.getImageInfo({
						src: url,
						success: res => {
							resolve(res.path);
						}
					})
				})
				// #endif
			},
			indexInitFun() {
				// #ifdef MP-WEIXIN
				return new Promise((resolve, reject) => {
					uni.onLocationChange((result) => {
						console.log(result)
						this.globalData.latitude = result.latitude;
						this.globalData.longitude = result.longitude;
						resolve(result)
					})
					uni.onLocationChangeError(err => {
						console.log(err)
						reject()
					})
				})
				// #endif
				// #ifdef APP
				console.log("`````````````````````````````````")
				return new Promise((resolve, reject) => {
					uni.getLocation({
						type: "gcj02",
						success: result => {

							this.globalData.latitude = result.latitude;
							this.globalData.longitude = result.longitude;
							resolve(result)
						},
						fail: err => {
							reject()
						}
					})
				})
				// #endif
			},
			getCateList() {
				return new Promise((resolve, reject) => {
					this.$u.api.industryList().then(res => {
						resolve(res)
					})
				})
			},
			getContentDetail(datas, type) {
				return new Promise((resolve, reject) => {
					if (type == "videoDetail") {
						console.log(datas)
						if (uni.getStorageSync("rmToken")) {
							this.$u.api.shareDetails(datas).then(res => {
								resolve(res)
							})
						} else {
							this.$u.api.indexShareDetails(datas).then(res => {
								resolve(res)
							})
						}
					} else if (type == "commentList") {
						this.$u.api.shareCommentList(datas).then(res => {
							resolve(res)
						})
					} else if (type == "replyList") {
						this.$u.api.shareCommentReplyList(datas).then(res => {
							resolve(res)
						})
					} else if (type == "replyAdd") {
						this.$u.api.shareCommentReplyAdd(datas).then(res => {
							uni.showToast({
								icon: 'none',
								title: "回复成功",
								duration: 2000
							})
							resolve(res)
						})
					} else if (type == "commentAdd") {
						this.$u.api.shareCommentAdd(datas).then(res => {
							uni.showToast({
								icon: 'none',
								title: "评论成功",
								duration: 2000
							})
							resolve(res)
						})
					} else if (type == "cancelCollect") {
						this.$u.api.userShareCollectionDel(datas).then(res => {
							uni.showToast({
								icon: 'none',
								title: "已取消收藏",
								duration: 2000
							})
							resolve(res)
						})
					} else if (type == "collectAdd") {
						console.log(datas)
						this.$u.api.userShareCollectionAdd(datas).then(res => {
							uni.showToast({
								icon: 'none',
								title: "已收藏",
								duration: 2000
							})
							console.log(res)
							resolve(res)
						})
					} else if (type == "giveCommentMain") {
						this.$u.api.shareCommentFabulousAdd(datas).then(res => {
							resolve(res)
						})
					} else if (type == "giveCommentSon") {
						this.$u.api.shareCommentReplyFabulousAdd(datas).then(res => {
							resolve(res)
						})
					} else if (type == "jbFun") {
						this.$u.api.shareReportAdd({
							data: datas
						}).then(res => {
							uni.showToast({
								icon: 'none',
								title: "举报成功",
								duration: 2000
							})
							resolve(res)
						})
					}
				})
			},
			getLocation() {
				let that = this;
				console.log("`````````````````````````````")
				// #ifdef MP-WEIXIN
				uni.getLocation({
					success: res => {
						console.log(res, 9999999)
						uni.startLocationUpdate({
							type: "gcj02",
							success: (res) => {
								console.log(res)
								uni.onLocationChange((result) => {
									this.globalData.latitude = result.latitude;
									this.globalData.longitude = result.longitude;
								})
								uni.onLocationChangeError(err => {
									console.log(err)
								})
							},
							fail: (err) => {
                this.globalData.latitude = 39.915156;
                this.globalData.longitude = 116.402544;
								console.log(err)
								this.checkGetLaction();
							}
						})
					},
					fail: err => {
						console.log(err, 199999999)
						if (err.errMsg == 'getLocation:fail:ERROR_NOCELL&WIFI_LOCATIONSWITCHOFF') {
							uni.showModal({
								content: "您未打开GPS定位或GPS信号弱，请调整后点击确认",
								success: rel => {
									if (rel.confirm) {
										that.getLocation();
									}
								}
							})
						}
						this.checkGetLaction()
					}
				})
				// #endif
				// #ifdef APP
				uni.getLocation({
					type: "gcj02",
					success: result => {
						this.globalData.latitude = result.latitude;
						this.globalData.longitude = result.longitude;

					},
					fail: err => {
            this.globalData.latitude = 39.915156;
            this.globalData.longitude = 116.402544;
						uni.showModal({
							content: "请检查手机定位是否开启并且授权给软件后重试！",
							success: rel => {
								if (rel.confirm) {
									this.getLocation();
								}
							}
						})
					}
				})
				// setInterval(() => {
				// 	uni.getLocation({
				// 		type: "gcj02",
				// 		success: result => {
				// 			this.globalData.latitude = result.latitude;
				// 			this.globalData.longitude = result.longitude;

				// 		}
				// 	})
				// }, 60000)
				// #endif
			},
			getTime(time, desc, type) {
				let dates = new Date(time);
				let year = dates.getFullYear();
				let month = (dates.getMonth() + 1) > 9 ? (dates.getMonth() + 1) : '0' + (dates.getMonth() + 1);
				let day = dates.getDate() > 9 ? dates.getDate() : '0' + dates.getDate();
				let hour = dates.getHours() > 9 ? dates.getHours() : '0' + dates.getHours();
				let min = dates.getMinutes() > 9 ? dates.getMinutes() : '0' + dates.getMinutes();
				let sec = dates.getSeconds() > 9 ? dates.getSeconds() : '0' + dates.getSeconds();
				if (type == 'day') {
					return year + desc + month + desc + day;
				} else {
					return year + desc + month + desc + day + ' ' + hour + ":" + min + ":" + sec;
				}
			},
			Rad(d) {
				//根据经纬度判断距离
				return d * Math.PI / 180.0;
			},
			getDistance(lat2, lng2) {
				var radLat1 = this.Rad(this.globalData.latitude);
				var radLat2 = this.Rad(lat2);
				var a = radLat1 - radLat2;
				var b = this.Rad(this.globalData.longitude) - this.Rad(lng2);
				var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math
					.pow(Math.sin(b / 2), 2)));
				s = s * 6378.137;
				s = Math.round(s * 10000) / 10000;
				s = s.toFixed(1); //保留两位小数
				console.log('经纬度计算的距离:' + s)
				return Number(s);
			},
			updataAvator(urls) {
				return new Promise((resolve, reject) => {
					let pos = urls.lastIndexOf('.');
					let filename = urls.substring(0, pos) // 文件名
					let extendName = urls.substring(pos + 1); // 扩展名
					let stroeAs = '' + timetamp + random_string(5) + '.' + extendName;
					if(extendName.toLocaleLowerCase() == "heic"){
						reject("不支持此格式的图片");
						return false;
					}
					uni.uploadFile({
						url: osshost,
						filePath: urls,
						fileType: 'image',
						name: 'file',
						formData: {
							'key': stroeAs,
							'policy': policyBase64,
							'OSSAccessKeyId': accessid,
							'success_action_status': '200', //让服务端返回200,不然，默认会返回204
							'signature': signature,
						},
						success(res) {
							resolve(stroeAs)
							// that.headimgurl = osshost + '/' + stroeAs;
						},
						fail(err) {
							reject(err)
						}
					})
				})

			},
      sendPushMes(obj) {
        let arr = {};
        arr.user_id = obj.user_id;
        arr.title = obj.title;
        arr.content = obj.content;
        arr.payload = obj.payload;//"/pages/pagethree/pages/myCreation/myCreation?form=shop&type=0";
        this.$u.api.appMessagePush(arr).then(res => {
          console.log("推送推送推送推送推送推送推送")
          console.log(res)
        })
      },
      setShareDetail(args){
        plus.runtime.arguments = null;
        let q = args;
        if (q.indexOf("?") != -1) {
          if (this.getArgs(q, "shareid")) {
            this.globalData.shareid = this.getArgs(q, "shareid");
          }
          if (this.getArgs(q, "cpid")) {
            this.globalData.cpid = this.getArgs(q, "cpid");
          }
          if (this.getArgs(q, "tgid")) {
            this.globalData.tgid = this.getArgs(q, "tgid");
          }
          if (this.getArgs(q, "mdid")) {
            this.globalData.mdid = this.getArgs(q, "mdid");
          }
          let type = this.getArgs(q, "type");
          this.globalData.type = this.getArgs(q, "mdid");
          if (type == 'cp') {
            uni.navigateTo({
              url: "/pages/pageone/pages/ActivityDetails/ActivityDetails?id=" + this.globalData
                  .cpid
            })
          }
          if (type == 'tg') {
            uni.navigateTo({
              url: "/pages/pagethree/pages/OfferDetails/OfferDetails?id=" + this.globalData.tgid
            })
          }
          if (type == 'tpnr') {
            this.globalData.nrid = this.getArgs(q, "nrid");
            uni.navigateTo({
              url: "/pages/pagetwo/pages/FindDetail/FindDetail?id=" + this.getArgs(q, "nrid")
            })
          }
          if (type == 'spnr') {
            this.globalData.nrid = this.getArgs(q, "nrid");
            uni.navigateTo({
              url: "/pages/pagefive/pages/VideoDetail/VideoDetail?id=" + this.getArgs(q, "nrid")
            })
          }
          if (type == 'gr') {
            uni.navigateTo({
              url: "/pages/pageone/pages/Business-card/Business-card?id=" + this.getArgs(q,
                  "usid")
            })
          }
        }
      }
		}
	}
</script>

<style lang="scss">
	@import "uview-ui/index.scss";
</style>
